<template>
  <div v-loading="wrapLoading" class="img-upload">
    <el-card>
      <input
        ref="file"
        type="file"
        accept="image/*"
        name="file"
        class="formFile"
        @change="fileChange"
      />
      <div>
        <div class="upload-wrap fcc" @click="doFileUpload">
          <img v-if="value" :src="value" />
          <i v-else class="el-icon-plus"></i>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { FileUpload } from "api/sys/file";

export default {
  model: {
    prop: "value",
    event: "change",
  },
  props: {
    value: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      // 文件上传面板loading
      wrapLoading: false,
    };
  },
  methods: {
    /**
     * 开始文件选择
     */
    doFileUpload() {
      this.$refs.file.click();
    },
    /**
     * 文件上传
     */
    async fileChange(event) {
      try {
        this.wrapLoading = true;
        const uploadFile = event.target.files[0];
        let formData = new FormData();
        formData.append("file", uploadFile);
        const { viewPath } = await FileUpload(formData, "sys-logo");
        console.log("viewPath", viewPath);
        this.$emit("change", viewPath);
      } catch (e) {
        console.log(e);
        // 清空文件上传
        event.target.value = "";
      } finally {
        this.wrapLoading = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.img-upload {
  .upload-wrap {
    width: 100%;
    height: 100px;
    border-radius: 6px;
    cursor: pointer;
    border: 1px dashed #c0ccda;
    background: #fbfdff;

    position: relative;
    &:hover {
      border-color: #409eff;
    }
    .el-icon-plus {
      font-size: 32px;
      color: #8c939d;
    }
    img {
      width: 100%;
      height: 100%;
      object-fit: contain;
      position: absolute;
    }
  }
}
</style>
